package com.qk.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.constant.BusinessStatusConstants;
import com.qk.constant.ClueStatusConstants;
import com.qk.constant.ClueTrackStatusConstants;
import com.qk.domain.clue.ClueDO;
import com.qk.domain.clue.ClueTrackRecordDO;
import com.qk.dto.clue.ClueDTO;
import com.qk.dto.clue.ClueFalseDTO;
import com.qk.dto.clue.ClueInfoUpdateDTO;
import com.qk.dto.clue.ClueQueryDTO;
import com.qk.entity.Business;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.enums.ParamEnum;
import com.qk.exception.CommonException;
import com.qk.mapper.BusinessMapper;
import com.qk.mapper.ClueTrackRecordMapper;
import com.qk.mapper.UserMapper;
import com.qk.service.ClueService;
import com.qk.mapper.ClueMapper;
import com.qk.util.CurrentUserContextHolders;
import com.qk.vo.clue.ClueVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author SweetHurt
 * @description 针对表【clue(线索表)】的数据库操作Service实现
 * @createDate 2025-10-14 11:27:44
 */
@Service
@SuppressWarnings("all")
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue>
        implements ClueService {

    @Autowired
    private ClueMapper clueMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;

    @Autowired
    private BusinessMapper businessMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateClueToBusiness(Integer id) {
        update(Wrappers.lambdaUpdate(Clue.class)
                .eq(Clue::getId, id)
                .set(Clue::getStatus, ClueStatusConstants.CONVERT_TO_BUSINESS)
                .set(Clue::getUpdateTime, LocalDateTime.now()));
        Clue clue = getById(id);
        if (ObjectUtil.isEmpty(clue)) {
            CommonException.throwException(ParamEnum.PARAM_ERROR);
        }
        Business business = BeanUtil.copyProperties(clue, Business.class, "id", "status", "userId", "status", "nextTime", "updateTime", "createTime");
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        business.setClueId(clue.getId());
        business.setUpdateTime(LocalDateTime.now());
        business.setCreateTime(LocalDateTime.now());
        businessMapper.insert(business);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateClueToFalse(ClueFalseDTO clueFalseDTO) {
        if (BeanUtil.hasNullField(clueFalseDTO, "remark")) {
            CommonException.throwException(ParamEnum.PARAM_NOT_NULL_ERROR);
        }
        clueTrackRecordMapper.insert(ClueTrackRecord.builder()
                .clueId(clueFalseDTO.getId())
                .userId(CurrentUserContextHolders.getId())
                .type(ClueTrackStatusConstants.FAKE_CLUE)
                .falseReason(clueFalseDTO.getReason())
                .record(clueFalseDTO.getRemark())
                .createTime(LocalDateTime.now())
                .build());
        return update(Wrappers.lambdaUpdate(Clue.class)
                .eq(Clue::getId, clueFalseDTO.getId())
                .set(Clue::getStatus, ClueStatusConstants.FALSE_CLUE)
                .set(Clue::getUpdateTime, LocalDateTime.now()));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateClue(ClueInfoUpdateDTO clueInfoUpdateDTO) {
        if (!ObjectUtil.isAllNotEmpty(clueInfoUpdateDTO, clueInfoUpdateDTO.getId(),
                clueInfoUpdateDTO.getSubject(), clueInfoUpdateDTO.getLevel(),
                clueInfoUpdateDTO.getNextTime(), clueInfoUpdateDTO.getRecord()
        )) {
            CommonException.throwException(ParamEnum.PARAM_NOT_NULL_ERROR);
        }
        Clue clue = BeanUtil.copyProperties(clueInfoUpdateDTO, Clue.class, "channel", "createTime");
        if (NumberUtil.equals(clue.getId(), ClueStatusConstants.WAIT_FOLLOW_UP)) {
            clue.setStatus(ClueStatusConstants.WAIT_FOLLOW_UP);
        }
        clue.setUserId(CurrentUserContextHolders.getId());
        clue.setUpdateTime(LocalDateTime.now());
        updateById(clue);
        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(clueInfoUpdateDTO, ClueTrackRecord.class, "id");
        clueTrackRecord.setClueId(clueInfoUpdateDTO.getId());
        clueTrackRecord.setUserId(CurrentUserContextHolders.getId());
        clueTrackRecord.setType(ClueTrackStatusConstants.NORMAL_FOLLOW_UP);
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecordMapper.insert(clueTrackRecord);
        return true;
    }

    @Override
    public ClueVO getClueInfoById(Integer id) {
        Clue clue = getById(id);
        if (ObjectUtil.isEmpty(clue)) {
            CommonException.throwException(ParamEnum.PARAM_ERROR);
        }
        ClueVO clueVO = BeanUtil.copyProperties(clue, ClueVO.class);
//        UserDO userDO = userMapper.selectById(clue.getUserId());
//        if (ObjectUtil.isNotEmpty(userDO)) {
//            clueVO.setAssignName(userDO.getName());
//        }
        clueVO.setAssignName(CurrentUserContextHolders.getName());
        List<ClueTrackRecord> clueTrackRecords = clueTrackRecordMapper.selectList(Wrappers.lambdaQuery(ClueTrackRecord.class).eq(ClueTrackRecord::getClueId, id));
        clueVO.setTrackRecords(clueTrackRecords.stream().map(clueTrackRecord -> {
            ClueTrackRecordDO clueTrackRecordDO = BeanUtil.copyProperties(clueTrackRecord, ClueTrackRecordDO.class);
//            if (ObjectUtil.isNotEmpty(userDO)) {
//                clueTrackRecordDO.setAssignName(userDO.getName());
//            }
            clueTrackRecordDO.setAssignName(CurrentUserContextHolders.getName());
            return clueTrackRecordDO;
        }).toList());
        return clueVO;
    }

    @Override
    public boolean assignClue(Integer clueId, Integer userId) {
        if (!ObjectUtil.isAllNotEmpty(clueId, userId)) {
            CommonException.throwException(ParamEnum.PARAM_NOT_NULL_ERROR);
        }
        return update(Wrappers.lambdaUpdate(Clue.class)
                .eq(Clue::getId, clueId)
                .set(Clue::getUserId, userId)
                .set(Clue::getStatus, ClueStatusConstants.WAIT_FOLLOW_UP));
    }

    @Override
    public boolean addClue(ClueDTO clueDTO) {
        if (!ObjectUtil.isAllNotEmpty(clueDTO, clueDTO.getPhone(), clueDTO.getChannel())) {
            CommonException.throwException(ParamEnum.PARAM_NOT_NULL_ERROR);
        }
        Clue clue = BeanUtil.copyProperties(clueDTO, Clue.class);
        clue.setUpdateTime(LocalDateTime.now());
        clue.setCreateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstants.WAIT_ALLOCATION);
        return save(clue);
    }

    @Override
    public PageResult<ClueDO> getClueByPage(ClueQueryDTO clueQueryDTO) {
        Page<ClueDO> list = clueMapper.selectClueByPage(new Page(clueQueryDTO.getPage(), clueQueryDTO.getPageSize()), clueQueryDTO);
        return PageResult.<ClueDO>builder()
                .total(Long.valueOf(list.getTotal()).intValue())
                .rows(list.getRecords())
                .build();
    }

}




